package com.aube.plugin.gallery.preview;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.graphics.Bitmap;
import android.graphics.drawable.GradientDrawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.aube.plugin.gallery.Comment;
import com.aube.plugin.gallery.CommentData;
import com.aube.plugin.gallery.CommentItemModel;
import com.aube.plugin.gallery.CommentModel;
import com.aube.plugin.gallery.PictureImp;
import com.aube.plugin.gallery.R;
import com.aube.plugin.gallery.emoji.EmoticonsUtils;
import com.huyn.baseframework.ImageLoader;
import com.huyn.baseframework.dynamicload.BlurViewDecorator;
import com.huyn.baseframework.model.BaseModel;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.SysUtil;
import com.huyn.baseframework.utils.UserUtil;
import com.huyn.baseframework.utils.Utils;

import java.lang.reflect.Constructor;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by huyaonan on 16/9/18.
 */
public class PictureDetailPresenter {

    private View mRoot;
    private View mBottomTool;
    private RelativeLayout mCommentLayout;
    private View mToolLayoutFavor, mToolLayoutComment, mToolLayoutShare;
    private ImageView mImageFavor, mImageComment, mImageShare;
    private TextView mTextFavor, mTextComment;
    private RecyclerView mCommentList;
    private EditText mCommentEdit;
    private ImageView mImageEmoji;
    private TextView mSend;
    private TextView mTips;
    private View mTipsDivider;

    private BlurViewDecorator mBlurBg;

    private SelfWrapLinearLayoutManager mLinearManager;

    private OnPresenter mPresenter;

    private PictureImp mCurrentPicture;

    public EmoticonsUtils emoticonUtils;

    private View mEmojiContainer, mEmojiBlank;

    private Context mContext;

    private CommentAdapter mCommentAdapter;

    private Resources mResources;

    private int mBottomToolHeight = 0;

    private static final String VALUE_EMOJI = "VALUE_EMOJI";
    private static final String VALUE_KEYBOARD = "VALUE_KEYBOARD";

    private int mTopbarHeight = 0;

    public PictureDetailPresenter(Context context) {
        this.mContext = context;
    }

    private boolean mIsReachTop = true;
    public void init(Resources resources, View root, OnPresenter presenter) {
        this.mRoot = root;
        this.mPresenter = presenter;
        this.mResources = resources;

        mBottomToolHeight = Utils.dip2px(mContext, 50);

        mBottomTool = root.findViewById(R.id.preview_bottom_funtion);
        mToolLayoutFavor = root.findViewById(R.id.layout_favor);
        mToolLayoutComment = root.findViewById(R.id.layout_comment);
        mToolLayoutShare = root.findViewById(R.id.layout_share);

        mImageFavor = (ImageView) root.findViewById(R.id.layout_favor_img);
        mImageComment = (ImageView) root.findViewById(R.id.layout_comment_img);
        mImageShare = (ImageView) root.findViewById(R.id.layout_share_img);

        mTextFavor = (TextView) root.findViewById(R.id.layout_favor_text);
        mTextComment = (TextView) root.findViewById(R.id.layout_comment_text);

        mCommentLayout = (RelativeLayout) root.findViewById(R.id.comment_detail);
        mCommentList = (RecyclerView) root.findViewById(R.id.comment_detail_recyclerview);
        mCommentList.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Utils.sysout("state:::::" + newState);
                if(newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if(mLinearManager.findFirstCompletelyVisibleItemPosition() == 0) {
                        boolean hideKeyboard = false;
                        if (emoticonUtils.isEmoticonsShowing()) {
                            emoticonUtils.hideEmoticonsView();
                            hideKeyboard = true;
                        }
                        if (emoticonUtils.isKeyBoardshowing()) {
                            emoticonUtils.hideKeyboard();
                            hideKeyboard = true;
                        }

                        if(!hideKeyboard && mIsReachTop) {
                            toggleCommentList(false, false);
                            mIsReachTop = true;
                        }
                        mIsReachTop = true;
                        return;
                    }

                    if(mLinearManager.findLastVisibleItemPosition() >= mCommentAdapter.getItemCount() - 3) {
                        onLoadMore(getCurrentPic());
                    }
                    mIsReachTop = true;
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                if(dy != 0)
                    mIsReachTop = false;
                else
                    mIsReachTop = true;
            }
        });

        mTopbarHeight = SysUtil.getStatusHeight(mContext) + Utils.dip2px(mContext, 48);
        View topGap = root.findViewById(R.id.comment_top_gap);
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) topGap.getLayoutParams();
        params.height = mTopbarHeight;

        mCommentEdit = (EditText) root.findViewById(R.id.comment_editor);
        mImageEmoji = (ImageView) root.findViewById(R.id.comment_emoji);
        mSend = (TextView) root.findViewById(R.id.comment_send);

        mEmojiBlank = root.findViewById(R.id.emoji_blank);
        mEmojiContainer = root.findViewById(R.id.comment_container);

        mTips = (TextView) root.findViewById(R.id.preview_tip);
        mTipsDivider = root.findViewById(R.id.preview_tip_divider);

        mLinearManager = new SelfWrapLinearLayoutManager(mContext);
        mLinearManager.setOrientation(LinearLayoutManager.VERTICAL);
        mLinearManager.setOnHeightSizeListener(new SelfWrapLinearLayoutManager.OnHeightSizeListener() {
            @Override
            public void onHeightMeasured(int height) {
                updateSizeHeight(height);
            }
        });
        mCommentList.setLayoutManager(mLinearManager);

        mCommentAdapter = new CommentAdapter();
        mCommentList.setAdapter(mCommentAdapter);

        if(presenter == null)
            return;

        mCommentAdapter.updateThemeColor(mPresenter.getThemeColor());

        attachBitmapToImageView(mImageFavor, R.drawable.icon_favor);
        attachBitmapToImageView(mImageComment, R.drawable.icon_comment);
        attachBitmapToImageView(mImageShare, R.drawable.icon_sharesmall);
        attachBitmapToImageView(mImageEmoji, R.drawable.icon_emoji);

        mEmojiContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(emoticonUtils.isKeyBoardshowing() || emoticonUtils.isEmoticonsShowing())
                    return;
                emoticonUtils.showKeyboard();
            }
        });

        mToolLayoutComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                expandCommentList();
            }
        });

        mToolLayoutFavor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.sysout("----------------check login toolbar favor");
                if(mPresenter.checkLogin())
                    doFavor();
            }
        });

        mToolLayoutShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doShare();
            }
        });

        mImageEmoji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String tag = (String) mImageEmoji.getTag();
                if(VALUE_EMOJI.equalsIgnoreCase(tag)) {
                    emoticonUtils.showEmoticonsView();
//                    attachBitmapToImageView(mImageEmoji, R.drawable.icon_keyboard);
//                    mImageEmoji.setTag(VALUE_KEYBOARD);
                } else {
                    mCommentEdit.requestFocus();
                    emoticonUtils.showKeyboard();
//                    attachBitmapToImageView(mImageEmoji, R.drawable.icon_emoji);
//                    mImageEmoji.setTag(VALUE_EMOJI);
                }
            }
        });
        mImageEmoji.setTag(VALUE_EMOJI);

        mCommentEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(StringUtils.isNotBlank(s.toString())) {
                    mSend.setClickable(true);
                    updateSendBg(true);
                } else {
                    mSend.setClickable(false);
                    updateSendBg(false);
                }
            }
        });

        mSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String conetnt = mCommentEdit.getEditableText().toString();
                if(StringUtils.isNotBlank(conetnt))
                    addComment(conetnt, getCurrentPic());
            }
        });

        updateSendBg(false);
        initEmojiUtils(resources);
        initBlurBg();

        GradientDrawable drawable = new GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP, new int[]{0x884e4c4c, 0x00000000});
        drawable.setShape(GradientDrawable.RECTANGLE);
        drawable.setGradientType(GradientDrawable.LINEAR_GRADIENT);
        mBottomTool.setBackgroundDrawable(drawable);
    }

    private void updateSendBg(boolean selected) {
        GradientDrawable gd = new GradientDrawable();
        gd.setCornerRadius(4);
        if(selected) {
            gd.setColor(0xffffcc00);
            mSend.setTextColor(0xff333333);
        } else {
            gd.setColor(0xff666666);
            mSend.setTextColor(0xffffffff);
        }
        mSend.setBackgroundDrawable(gd);
    }

    private void initBlurBg() {
        try {
            Class<? extends BlurViewDecorator> clazz = mContext.getClassLoader().loadClass("com.aube.views.BlurringView").asSubclass(BlurViewDecorator.class);

            Constructor<? extends BlurViewDecorator> constructor = clazz.getConstructor(Context.class);

            mBlurBg = constructor.newInstance(mContext);
            mBlurBg.setOverlayColor(0xcc202020);
            mBlurBg.setBlurredView(mPresenter.getBlurView());
//            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, mBottomToolHeight);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            params.setMargins(0, mTopbarHeight, 0, 0);

            mCommentLayout.addView(mBlurBg, 0, params);
        } catch (Exception e) {
            e.printStackTrace();
//            throw new IllegalStateException("Could not load BlurringView", e);
        }
    }

    private int mLastHeight = 0;
    private void updateSizeHeight(int height) {
        if(mBlurBg == null || height == mLastHeight - mBottomToolHeight)
            return;

        mLastHeight = height + mBottomToolHeight;
//        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mBlurBg.getLayoutParams();
//        params.height = mLastHeight;
        Utils.sysout("=======update size height:" + (mRoot.getHeight() - mTopbarHeight - mLastHeight));
        mBlurBg.setTranslationY(mRoot.getHeight() - mTopbarHeight - mLastHeight);
        mBlurBg.invalidateSelf();
    }

    private void attachBitmapToImageView(ImageView imageView, int resId) {
        imageView.setImageBitmap(mPresenter.onLoadBitmap(resId));
    }

    private EmoticonsUtils.OnEmoticonsStateListener emotionsListener = new EmoticonsUtils.OnEmoticonsStateListener() {

        @Override
        public void onShowing() {
            attachBitmapToImageView(mImageEmoji, R.drawable.icon_keyboard);
            mImageEmoji.setTag(VALUE_KEYBOARD);
        }

        @Override
        public void onDismiss() {
            attachBitmapToImageView(mImageEmoji, R.drawable.icon_emoji);
            mImageEmoji.setTag(VALUE_EMOJI);
        }
    };

    private void initEmojiUtils(Resources resources) {
        Utils.sysout("-------------------------------------init emoticons");
        emoticonUtils = new EmoticonsUtils();
        emoticonUtils.init(mContext, resources, mRoot, mEmojiContainer, mCommentEdit, mEmojiBlank);

        emoticonUtils.setOnEmoticonsStateListener(emotionsListener);
        emoticonUtils.setOnKeyboardStateListener(new EmoticonsUtils.OnKeyboardStateListener() {

            @Override
            public void onShowing() {
            }

            @Override
            public void onDismiss() {
            }
        });
        emoticonUtils.setOnEmoticonKeyboardHeightListener(new EmoticonsUtils.OnEmoticonKeyboardHeightListener() {
            @Override
            public void onHeightChanged(int height, boolean open) {
                if(mBlurBg == null)
                    return;
                Utils.sysout("=====" + open);
                if(open) {
//                    mBlurBg.setTranslationY(-height);
//                    mBlurBg.invalidateSelf();
//                    if(-height == mBlurBg.getTranslationY())
//                        return;
//                    animUp(-height);

                    int listHeight = mCommentList.getHeight();
                    int listToMove = mRoot.getHeight() - mTopbarHeight - mBottomToolHeight - listHeight;
                    Utils.sysout("------list height:" + listHeight + "/" + (mRoot.getHeight() - mTopbarHeight - mBottomToolHeight));
                    if(listToMove > 0) {
                        Utils.sysout("------list to move:" + listToMove);
                        if(listToMove > height)
                            listToMove = height;
                        int targetTranslationY = mRoot.getHeight() - mTopbarHeight - mBottomToolHeight - listHeight - height;
                        Utils.sysout("------bg to move:" + targetTranslationY);
                        if(targetTranslationY < 0)
                            targetTranslationY = 0;

                        Utils.sysout("+++++" + mRoot.getHeight() + "/" + mTopbarHeight + "/" + mBottomToolHeight + "/" + listHeight + "/" + height);
                        if(listToMove < height) {
//                            animUp(height + mBottomToolHeight + mTopbarHeight - listToMove, targetTranslationY);
//                            animUp(height, targetTranslationY);
                            animUp(listToMove, targetTranslationY);
                            changeIntputBgColor(true);
                        } else {
                            animUp(listToMove, targetTranslationY);
                        }
                    } else {
//                        animUp(height, 0);
                        changeIntputBgColor(true);
                    }
                } else {
//                    mBlurBg.setTranslationY(0);
                    mBlurBg.setTranslationY(mRoot.getHeight() - mTopbarHeight - mLastHeight);
                    mCommentList.setTranslationY(0);
                    mBlurBg.invalidateSelf();

                    changeIntputBgColor(false);

                    if(mCommentAdapter==null || mCommentAdapter.getItemCount()==0) {
                        //show tools
                        toggleCommentList(false, false);
                    }
                }
            }
        });
    }

    private void changeIntputBgColor(boolean listUp) {
        if(listUp)
            mEmojiContainer.setBackgroundColor(0xff242424);
        else
            mEmojiContainer.setBackgroundColor(0x1affffff);
    }

    private void animUp(final int listToMove, final int bgToMove) {
        final float startTranslationY = mBlurBg.getTranslationY();
        final float startListY = mCommentList.getTranslationY();
//        if(Math.abs(startTranslationY - bgToMove) <= 2)
//            return;
        Utils.sysout(startTranslationY + "------" + startListY);
        ValueAnimator obj = ValueAnimator.ofInt().ofFloat(0, 1);
        obj.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                mBlurBg.setTranslationY(startTranslationY + value*(bgToMove - startTranslationY));
                mBlurBg.invalidateSelf();
                mCommentList.setTranslationY(startListY + value*(-listToMove - startListY));
            }
        });
        obj.setDuration(200);
        obj.start();
    }

    private void doFavor() {
        if(FavorManager.getInstance().isFavored(getCurrentPic())) {
            FavorManager.getInstance().update(getCurrentPic(), false);
            FavorManager.getInstance().addFavorCount(getCurrentPic(), FavorManager.getInstance().getFavorCount(getCurrentPic()) - 1);
        } else {
            FavorManager.getInstance().update(getCurrentPic(), true);
            FavorManager.getInstance().addFavorCount(getCurrentPic(), FavorManager.getInstance().getFavorCount(getCurrentPic()) + 1);
        }

        updateFavorState();

        HashMap<String, String> params = new HashMap<>();
        params.put("method", "com.aube.comment.praise");
        params.put("relatedid", getCurrentPic());
        params.put("type", mPresenter.getType());
        mPresenter.onHttpRequest(params, BaseModel.class, null, new Response.Listener<BaseModel>() {
            @Override
            public void onResponse(BaseModel response) {
            }

            @Override
            public void onErrorResponse(VolleyError error) {
            }

            @Override
            public void onStart() {
            }
        });
    }

    private void doFavor(String commentId, int pos) {
        if("-1".equalsIgnoreCase(commentId) || StringUtils.isBlank(commentId))
            return;

        if(FavorManager.getInstance().isFavored(commentId)) {
            FavorManager.getInstance().update(commentId, false);
            FavorManager.getInstance().addFavorCount(commentId, FavorManager.getInstance().getFavorCount(commentId) - 1);
        } else {
            FavorManager.getInstance().update(commentId, true);
            FavorManager.getInstance().addFavorCount(commentId, FavorManager.getInstance().getFavorCount(commentId) + 1);
        }

        mCommentAdapter.notifyItemChanged(pos);

        HashMap<String, String> params = new HashMap<>();
        params.put("method", "com.aube.comment.praise");
        params.put("relatedid", commentId);
        params.put("type", mPresenter.getType());
        mPresenter.onHttpRequest(params, BaseModel.class, null, new Response.Listener<BaseModel>() {
            @Override
            public void onResponse(BaseModel response) {
            }

            @Override
            public void onErrorResponse(VolleyError error) {
            }

            @Override
            public void onStart() {
            }
        });
    }

    private void doShare() {
        mPresenter.onOpenShareLayout();
    }

    private void expandCommentList() {
        if(mCommentLayout.getVisibility() != View.VISIBLE) {
            toggleCommentList(true, false);

            if(mBlurBg != null)
                mBlurBg.invalidateSelf();

            if(mCommentAdapter==null || mCommentAdapter.getItemCount()==0) {
                //show keyboard
                emoticonUtils.showKeyboard();
            }
        }
    }

    private void fadeInOrOut(final View view, final boolean in) {
        ObjectAnimator animator = ObjectAnimator.ofFloat(view, "alpha", in ? 0f : 1f, in ? 1f : 0f);
        animator.setDuration(200);
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                if(!in)
                    view.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationStart(Animator animation) {
                if(in)
                    view.setVisibility(View.VISIBLE);
            }
        });
        animator.start();
    }

    private void translateList(boolean expand) {
//        ObjectAnimator animator = ObjectAnimator.ofFloat(mCommentList, "translationY", expand ? mCommentList.getHeight() : 0, expand ? 0 : mCommentList.getHeight());
//        animator.setDuration(200);
//        animator.start();
        Animation anim = AnimationLoader.loadAnimation(mContext, mResources, expand ? R.anim.bottom_in : R.anim.bottom_out);
        anim.setDuration(200);
        mCommentList.startAnimation(anim);
        mBlurBg.startAnimation(anim);
    }

    private void manageBottomTool(boolean visible, boolean exit) {
        if(!exit)
            fadeInOrOut(mBottomTool, visible);
        else
            mBottomTool.setVisibility(View.VISIBLE);
        mCommentEdit.clearFocus();
        mSend.requestFocus();
    }

    private String getCurrentPic() {
        if(mCurrentPicture == null)
            return "";
        return mCurrentPicture.picid;
    }

    private int mCurrentCommentCount=0;
    /**
     * type photo/actor
     * commentType hot/recent
     * @param picture
     */
    public void update(PictureImp picture) {
        //没有切换
        if(picture.picid.equalsIgnoreCase(getCurrentPic()))
            return;

        mCurrentCommentCount = picture.commentCount;

        mCommentEdit.setText("");
        if(mCommentLayout.getVisibility() == View.VISIBLE) {
            toggleCommentList(false, false);

            if(emoticonUtils.isEmoticonsShowing())
                emoticonUtils.hideEmoticonsView();
            if(emoticonUtils.isKeyBoardshowing())
                emoticonUtils.hideKeyboard();
        }

        mCommentAdapter.clear();

        this.mCurrentPicture = picture;

        mTips.setText(picture.getDesc());
        if(StringUtils.isNotBlank(picture.getDesc())) {
            mTipsDivider.setVisibility(View.VISIBLE);
        } else {
            mTipsDivider.setVisibility(View.GONE);
        }

        updateFavorState();

        HashMap<String, String> params = new HashMap<>();
        params.put("method", "com.aube.comment.commentList");
        params.put("relatedid", picture.picid);
        params.put("type", mPresenter.getType());
        params.put("commentType", "recent");
        params.put("maxnum", "20");
        params.put("from", "0");
        mPresenter.onHttpRequest(params, CommentModel.class, null, new Response.Listener<CommentModel>() {
            @Override
            public void onResponse(CommentModel response) {
                if(response != null && response.success())
                    setupCommemtList(response.data, 0);
            }

            @Override
            public void onErrorResponse(VolleyError error) {
            }

            @Override
            public void onStart() {
            }
        });
    }

    private AtomicBoolean mLoading = new AtomicBoolean(false);
    private void onLoadMore(final String id) {
        if(mLoading.get())
            return;
        if(mCommentAdapter.getItemCount()-1 >= mCurrentCommentCount)
            return;

        HashMap<String, String> params = new HashMap<>();
        params.put("method", "com.aube.comment.commentList");
        params.put("relatedid", id);
        params.put("type", mPresenter.getType());
        params.put("commentType", "recent");
        params.put("maxnum", "20");
        params.put("from", mCommentAdapter.getItemCount()-1+"");
        mPresenter.onHttpRequest(params, CommentModel.class, null, new Response.Listener<CommentModel>() {
            @Override
            public void onResponse(CommentModel response) {
                mLoading.set(false);
                if(response != null && response.success() && getCurrentPic().equalsIgnoreCase(id))
                    setupCommemtList(response.data, 0);
            }

            @Override
            public void onErrorResponse(VolleyError error) {
                mLoading.set(false);
            }

            @Override
            public void onStart() {
            }
        });
    }

    private void updateFavorState() {
//        mTextFavor.setText(picture.praiseCount + "");
//        mTextComment.setText(picture.commentCount + "");
//        attachBitmapToImageView(mImageFavor, picture.isPraised() ? R.drawable.icon_favor_yes : R.drawable.icon_favor);
        int favorCount = FavorManager.getInstance().getFavorCount(getCurrentPic());
        int commentCount = FavorManager.getInstance().getCommentCount(getCurrentPic());
        mTextFavor.setText(favorCount > 0 ? (favorCount + "个赞") : "点赞");
        mTextComment.setText(commentCount > 0 ? (commentCount + "条评论") : "评论");
        attachBitmapToImageView(mImageFavor, FavorManager.getInstance().isFavored(getCurrentPic()) ? R.drawable.icon_favor_yes : R.drawable.icon_favor);
    }

    private void setupCommemtList(CommentData data, int from) {
        if(data != null && data.totalCount <= 0)
            return;

        FavorManager.getInstance().update(data.commentList);

        if(data.getId().equalsIgnoreCase(getCurrentPic())) {
            if(from > 0) {
                mCommentAdapter.refresh(data.commentList);
            } else {
                mCommentAdapter.updateCount(data.totalCount);
                mCommentAdapter.append(data.commentList);
            }
        }
    }

    private Comment setupComment(String cData) {
        Comment comment = new Comment();
        comment.commentId = "-1";
        comment.commentCount = 0;
        comment.content = cData;
        comment.nickName = UserUtil.getUserName();
        comment.headPic = UserUtil.getUserHead();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        comment.createTime = sdf.format(new Date());
        return comment;
    }

    public void addComment(String comment, final String relatedId) {
        Utils.sysout("----------------check login addcomment");
        if(!mPresenter.checkLogin())
            return;

        int count = FavorManager.getInstance().getCommentCount(getCurrentPic()) + 1;
        FavorManager.getInstance().addCommentCount(getCurrentPic(), count);
        updateFavorState();

        mCommentAdapter.updateCount(count);

        //add to list
        mCommentAdapter.append(setupComment(comment));

        //clear input
        mCommentEdit.setText("");
        emoticonUtils.hideKeyboard();
        emoticonUtils.hideEmoticonsView();

        HashMap<String, String> params = new HashMap<>();
        params.put("method", "com.aube.comment.save");
        params.put("relatedid", relatedId);
        params.put("type", mPresenter.getType());
        params.put("title", "");
        params.put("content", comment);
        params.put("images", "");
        mPresenter.onHttpRequest(params, CommentItemModel.class, null, new Response.Listener<CommentItemModel>() {
            @Override
            public void onResponse(CommentItemModel response) {
                if(response != null && response.success()) {
                    if(response.getRelatedId().equalsIgnoreCase(getCurrentPic())) {
                        mCommentAdapter.update(response.data);
                    }
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {
            }

            @Override
            public void onStart() {
            }
        });
    }

    public boolean onBackpressed() {
        if(mCommentLayout.getVisibility() == View.VISIBLE) {
            if (emoticonUtils.isKeyBoardshowing()) {
                emoticonUtils.hideKeyboard();
                return true;
            }
            if (emoticonUtils.hideEmoticonsView(true))
                return true;

            toggleCommentList(false, false);
            return true;
        }
        return false;
    }

    public void onDestroy() {
        if(emoticonUtils.isKeyBoardshowing())
            emoticonUtils.hideKeyboard();
        if(emoticonUtils.isEmoticonsShowing())
            emoticonUtils.hideEmoticonsView();
        mCommentEdit.setText("");
        toggleCommentList(false, true);
    }

    public void toggleCommentList(boolean expand, boolean exit) {
//        if(expand) {
//            mCommentLayout.setVisibility(View.VISIBLE);
//        } else {
//            mCommentLayout.setVisibility(View.GONE);
//        }
        fadeInOrOut(mCommentLayout, expand);
        translateList(expand);
        manageBottomTool(!expand, exit);
    }

    private class CommentAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private List<Comment> mContents;
        private int count;
        private int themeColor;

        public CommentAdapter() {}

        public void updateCount(int count) {
            this.count = count;
        }

        public void updateThemeColor(int themeColor) {
            this.themeColor = themeColor;
        }

        public void clear() {
            if(mContents != null)
                mContents.clear();
            notifyDataSetChanged();
        }

        public CommentAdapter(int count, int themeColor) {
            this.count = count;
            this.themeColor = themeColor;
        }

        public void refresh(List<Comment> comments) {
            this.mContents = comments;
            notifyDataSetChanged();
        }

        public void append(List<Comment> comments) {
            if(mContents == null)
                mContents = comments;
            else
                mContents.addAll(comments);
            notifyDataSetChanged();
        }

        public void append(Comment comment) {
            if(mContents == null)
                mContents = new ArrayList<>();
            mContents.add(0, comment);
            notifyItemInserted(0);
            notifyItemChanged(0);
        }

        public void update(Comment comment) {
            if(mContents == null)
                mContents = new ArrayList<>();
            int i=1;
            for(Comment item : mContents) {
                if(item.commentId.equalsIgnoreCase("-1")) {
                    item.update(comment);
                    notifyItemChanged(i);
                }
                i++;
            }
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int type) {
            if(type == 0) {
                View view = getView(R.layout.comment_head);
                viewGroup.addView(view);
                return new CommentHeadHolder(view);
            } else {
                View view = getView(R.layout.comment_item);
                viewGroup.addView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                return new CommentItemHolder(view);
            }
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int i) {
            if(i > 0)
                ((CommentItemHolder) viewHolder).update(getComment(i), i, getItemCount());
            else
                ((CommentHeadHolder) viewHolder).update("全部" + count + "条评论", themeColor);
        }

        @Override
        public int getItemViewType(int position) {
            if(position == 0)
                return 0;
            return 1;
        }

        @Override
        public int getItemCount() {
            int size = mContents == null ? 0 : mContents.size();
            return size == 0 ? 0 : size + 1;
        }

        private Comment getComment(int position) {
            return mContents.get(position - 1);
        }

    }

    private View getView(int resId) {
        XmlResourceParser parser = mResources.getLayout(resId);

        View view;
        try {
            view = LayoutInflater.from(mContext).inflate(parser, null, false);
        } finally {
            parser.close();
        }

        return view;
    }

    private class CommentHeadHolder extends RecyclerView.ViewHolder {

        private View mFlag;
        private TextView mTitle;

        public CommentHeadHolder(View itemView) {
            super(itemView);

            mFlag = itemView.findViewById(R.id.header_flag);
            mTitle = (TextView) itemView.findViewById(R.id.header_widget_title);
        }

        public void update(String s, int themeColor) {
            mFlag.setBackgroundColor(themeColor);
            mTitle.setText(s);
        }

    }

    private class CommentItemHolder extends RecyclerView.ViewHolder {

        private LinearLayout mHeadLayout;
        private TextView mName, mTime, mContent, mFavorCount;
        private ImageView mFavor;
        private ImageView mLogo;
        private View mHead, mDivider, mFavorLayout;

        public CommentItemHolder(View itemView) {
            super(itemView);

            mHead = itemView.findViewById(R.id.comment_item_head);
            mHeadLayout = (LinearLayout) itemView.findViewById(R.id.comment_item_icon);
            mName = (TextView) itemView.findViewById(R.id.comment_item_name);
            mTime = (TextView) itemView.findViewById(R.id.comment_item_time);
            mContent = (TextView) itemView.findViewById(R.id.comment_item_content);
            mFavor = (ImageView) itemView.findViewById(R.id.comment_item_favor);
            mFavorCount = (TextView) itemView.findViewById(R.id.comment_item_favor_count);
            mDivider = itemView.findViewById(R.id.comment_divider);
            mFavorLayout = itemView.findViewById(R.id.comment_item_favor_layout);
            mLogo = (ImageView) itemView.findViewById(R.id.comment_item_logo);
        }

        public void update(final Comment comment, final int pos, int count) {
            mName.setText(comment.nickName);
            mTime.setText(comment.createTime);
            mContent.setText(comment.content);
            attachBitmapToImageView(mLogo, R.drawable.bk_default);
            ImageLoader.getInstance(mContext).fillRoundImage(mLogo, comment.headPic);
//            attachBitmapToImageView(mFavor, comment.isPraised() ? R.drawable.icon_favor_yes : R.drawable.icon_favor);
            attachBitmapToImageView(mFavor, FavorManager.getInstance().isFavored(comment.commentId) ? R.drawable.icon_favor_yes : R.drawable.icon_favor);

            int favorCount = FavorManager.getInstance().getFavorCount(comment.commentId);
            mFavorCount.setText((favorCount > 0 ? favorCount : "") + "");

            mFavorLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Utils.sysout("----------------check login comment favor");
                    if(mPresenter.checkLogin()) {
                        doFavor(comment.commentId, pos);
                    }
                }
            });

            if(pos < count-1)
                mDivider.setVisibility(View.VISIBLE);
            else
                mDivider.setVisibility(View.GONE);
        }

    }

    public interface OnPresenter {
        public Bitmap onLoadBitmap(int res);
        public void onHttpRequest(HashMap<String, String> params, Class clazz, String tag, Response.Listener listener);
        public void onOpenShareLayout();
        public View getBlurView();
        public int getThemeColor();
        public String getType();
        public boolean checkLogin();
    }

}
